﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using OVS.Business;
using OVS.CoreDomain;
using OVS.CoreDomain.Business;

namespace OVS
{
    public partial class ManageElections : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["LoggedIn"] == null)
            {
                Response.Write("Please login!");
                Response.End();
            }
            else
            {
                ILoggedin loggedIn = (ILoggedin)Session["LoggedIn"];
                if (!loggedIn.IsAdmin)
                {
                    Response.Write("You must be logged in as Admin to view this page!");
                    Response.End();
                }
            }
            if (!Page.IsPostBack)
            {

                if (Request.QueryString["Mode"] != null)
                {
                    string _mode = Request.QueryString["Mode"].ToString();

                    ViewState["Mode"] = _mode;
                    string _electionId = Request.QueryString["electionId"].ToString();
                    ViewState["ElectionId"] = _electionId;


                    PopulateElection(int.Parse(_electionId));
                }
            }
        }


        protected void PopulateElection(int electionId)
        {
            IBusinessElection businessElection = new BusinessElection();
            IElection election = businessElection.GetElection(electionId);

            txtname.Text = election.ElectionDescription;
            txtStartDate.Text = election.ElectionDate.ToShortDateString();
            txtEndDate.Text = election.ResultDate.ToShortDateString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            IBusinessElection businessElection = new BusinessElection();
            IElection election = new Election();
            election.ElectionDescription = txtname.Text.Trim();
            election.ElectionDate = Convert.ToDateTime(txtStartDate.Text);
            election.ResultDate = Convert.ToDateTime(txtEndDate.Text);

            if ((ViewState["Mode"] != null) && (ViewState["Mode"].ToString() == "Edit"))
            {
                election.ElectionId = int.Parse(ViewState["ElectionId"].ToString());
                businessElection.UpdateElection(election);
            }
            else
                businessElection.AddElection(election);

            lblMsg.Text = "Election details saved!";

            Reset();

        }



        protected void btnReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        protected void Reset()
        {
            txtname.Text = string.Empty;
            txtStartDate.Text = string.Empty;
            txtEndDate.Text = string.Empty;
        }

    }
}
